﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;

using Global.Class.Library;

namespace DataAccessLayer
{
    public static class GlobalDataObjectAction
    {
        /// <summary>
        /// Get Save Conflict of a Data Entry (Data Transaction Object)
        /// </summary>
        /// <param name="storedProcedureName"></param>
        /// <param name="findIdentityID"></param>
        /// <returns></returns>
        public static bool SaveConflict(string storedProcedureName, int findIdentityID)
        {
            SqlParameter[] sqlParameter = new SqlParameter[1];
            sqlParameter[0] = new SqlParameter("FindIdentityID", findIdentityID); sqlParameter[0].SqlDbType = SqlDbType.Int; sqlParameter[0].Direction = ParameterDirection.Input;

            int existIdentityID = SQLDatabase.GetReturnValue(storedProcedureName, CommandType.StoredProcedure, sqlParameter);
            return existIdentityID != -1;
        }


        public static string NewIDReference(string tableName, string referenceFieldName, long startInPosition)
        {
            return GlobalDataObjectAction.NewIDReference(tableName, referenceFieldName, startInPosition, "");
        }

        public static string NewIDReference(string tableName, string referenceFieldName, long startInPosition, string stringWhereClause)
        {
            int lReferenceID; string lReferencePrefix = "U";
            try
            {
                DataTable lRec = SQLDatabase.GetDataTable("SELECT MAX(CAST( SUBSTRING(" + referenceFieldName + ", " + startInPosition + ", CASE PATINDEX('%-%', " + referenceFieldName + ") WHEN 0 THEN LEN(" + referenceFieldName + ") - 1 ELSE PATINDEX('%-%', " + referenceFieldName + ") - " + startInPosition + " END) AS FLOAT ) ) AS ReferenceIDMax FROM " + tableName + stringWhereClause);

                if (lRec.Rows.Count > 0)
                    if (lRec.Rows[0]["ReferenceIDMax"] == null)
                        lReferenceID = 1;
                    else
                        lReferenceID = (int)(double)lRec.Rows[0]["ReferenceIDMax"] + 1;
                else
                    lReferenceID = 1;


                return lReferencePrefix + lReferenceID.ToString("00000");
            }
            catch (Exception exception)
            {
                throw exception;
            }
        }




    }
}
